﻿using System;
using System.Text;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;


namespace LenderClearingHouse
{
    public partial class Archive : GridPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckedProperties.Clear();   
            }
            RadAjaxManager.AjaxSettings.AddAjaxSetting(Grid, Grid);
        }

        public static List<long> CheckedProperties
        {
            get
            {
                List<long> result = HttpContext.Current.Session["CheckedProperties"] as List<long>;
                if (result == null)
                {
                    result = new List<long>();
                    HttpContext.Current.Session["CheckedProperties"] = result;
                }

                return result;
            }
        }

        protected override SourcePage GetSourcePage()
        {
            return SourcePage.Archive;
        }

        protected override SqlDataSource GetSqlDataSource()
        {
            return sqlDataSource;
        }

        protected override ListFilterControl GetListFilterControl()
        {
            return null;
        }

        protected override Control GetGridContainer()
        {
            return phGrid;
        }

        protected override string GetDataSourceID()
        {
            return sqlDataSource.ID;
        }

        protected override void CreateColumns(GridColumnCollection columns)
        {
            int newIndex = 1;
            GridTemplateColumn gtc;

            gtc = new GridTemplateColumn()  
            {   
                UniqueName = "Checked",
                ItemTemplate = new CheckBoxedColumn("Checked"), 
                AllowFiltering = false     
            };         
            gtc.HeaderStyle.Width = Unit.Pixel(30); 
            columns.Add(gtc);  
            
            ++newIndex;    

            base.CreateColumns(columns);

            GridBoundColumn col = new GridBoundColumn();
            col.DataField = "VO";
            col.HeaderText = "v/o";
            col.ConvertEmptyStringToNull = false;
            col.EditFormColumnIndex = 1;
            col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
            col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
            columns.Add(col);

            gtc = new GridTemplateColumn()
            {
                UniqueName = "MaxBid",
                HeaderText = "MaxBd",
                ItemTemplate = new DollarColumn("MaxBid"),
                EditItemTemplate = new CurrencyColumnEdit("MaxBid"),
                ConvertEmptyStringToNull = false,
                EditFormColumnIndex = 2,
                DataField = "MaxBid",
                SortExpression = "MaxBid"
            };
            gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
            gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
            columns.Add(gtc);

            gtc = new GridTemplateColumn()
            {
                UniqueName = "EstVal",
                HeaderText = "EstVal",
                ItemTemplate = new DollarColumn("EstVal"),
                EditItemTemplate = new CurrencyColumnEdit("EstVal"),
                ConvertEmptyStringToNull = false,
                EditFormColumnIndex = 1,
                DataField = "EstVal",
                SortExpression = "EstVal"
            };
            gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
            gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
            columns.Add(gtc);

            col = new GridBoundColumn();
            col.DataField = "Site";
            col.HeaderText = "Site";
            col.ConvertEmptyStringToNull = false;
            col.EditFormColumnIndex = 1;
            col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
            col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
            columns.Add(col);

            col = new GridBoundColumn();
            col.DataField = "OnOff";
            col.HeaderText = "On/Off";
            col.ConvertEmptyStringToNull = false;
            col.EditFormColumnIndex = 1;
            col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
            col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
            columns.Add(col);

            col = new GridBoundColumn();
            col.DataField = "FromList";
            col.HeaderText = "FromList";
            col.ConvertEmptyStringToNull = false;
            col.EditFormColumnIndex = 1;
            col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
            col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
            columns.Add(col);

            Utilities.RemoveColumn(columns, "Address");

            col = new GridBoundColumn();
            col.DataField = "PropertyLocation";
            col.HeaderText = "Address";
            col.UniqueName = "Address";
            col.ConvertEmptyStringToNull = false;
            col.ReadOnly = true;
            col.Display = true;
            col.HeaderStyle.Width = Unit.Pixel(150);
            columns.Add(col);

            Utilities.MoveColumn(columns, "Address", ref newIndex);
            Utilities.MoveColumn(columns, "AuctionDate", ref newIndex);
            Utilities.MoveColumn(columns, "Trustee", ref newIndex);
            Utilities.MoveColumn(columns, "TsNumber", ref newIndex);
            Utilities.MoveColumn(columns, "Apn", ref newIndex);
            Utilities.MoveColumn(columns, "PropertyLocation", ref newIndex);
            Utilities.MoveColumn(columns, "ZipCode", ref newIndex);
            Utilities.MoveColumn(columns, "VO", ref newIndex);
            Utilities.MoveColumn(columns, "Stories", ref newIndex);
            Utilities.MoveColumn(columns, "ConstructYear", ref newIndex);
            Utilities.MoveColumn(columns, "TotalSqft", ref newIndex);
            Utilities.MoveColumn(columns, "LotSize", ref newIndex);
            Utilities.MoveColumn(columns, "Bedrooms", ref newIndex);
            Utilities.MoveColumn(columns, "Bathrooms", ref newIndex);
            Utilities.MoveColumn(columns, "GarageSqft", ref newIndex);
            Utilities.MoveColumn(columns, "Pool", ref newIndex);
            Utilities.MoveColumn(columns, "Spa", ref newIndex);
            Utilities.MoveColumn(columns, "EstimatedBid", ref newIndex);
            Utilities.MoveColumn(columns, "TsOpeningBid", ref newIndex);
            Utilities.MoveColumn(columns, "MaxBid", ref newIndex);
            Utilities.MoveColumn(columns, "EstVal", ref newIndex);
            Utilities.MoveColumn(columns, "Nos", ref newIndex);
            Utilities.MoveColumn(columns, "Liens", ref newIndex);
            Utilities.MoveColumn(columns, "Tax", ref newIndex);
            Utilities.MoveColumn(columns, "Site", ref newIndex);
            Utilities.MoveColumn(columns, "OnOff", ref newIndex);
            Utilities.MoveColumn(columns, "MiscNotes", ref newIndex);
            Utilities.MoveColumn(columns, "AssessorDesc", ref newIndex);
            Utilities.MoveColumn(columns, "Hoa", ref newIndex);
            Utilities.MoveColumn(columns, "PrelistStatus", ref newIndex);
            Utilities.MoveColumn(columns, "PurchasePrice", ref newIndex);
            Utilities.MoveColumn(columns, "RehabCosts", ref newIndex);
            Utilities.MoveColumn(columns, "LandUse", ref newIndex);
            Utilities.MoveColumn(columns, "Phase", ref newIndex);
            Utilities.MoveColumn(columns, "ListingStatus", ref newIndex);
            Utilities.MoveColumn(columns, "Client", ref newIndex);
            Utilities.MoveColumn(columns, "CloseDate", ref newIndex);
            Utilities.MoveColumn(columns, "Source", ref newIndex);
            Utilities.MoveColumn(columns, "DateRecorded", ref newIndex);
            
            
            columns.Remove(columns.FindByDataField("EscrowCompany"));

            int index = Utilities.GetColumnIndex(columns, "MiscNotes") + 1;
            columns.Insert(index, Utilities.CreateBoundColumn("NdsCorp_SaleDate", "National Default – Sale Date Previous/Projected", true));
            columns.Insert(index, Utilities.CreateBoundColumn("PriorityPost_Status", "Priority Post – Status"));
            columns.Insert(index, Utilities.CreateBoundColumn("LPS_SalesStatus", "LPS - Sales Status"));
            columns.Insert(index, Utilities.CreateTemlateDateColumn("ReconTrust_DateOfSale", "Recon Trust – Date of Sale", 0));
        }

        protected void DeleteFromArchive_Click(object sender, EventArgs e)
        {
            var master = new List<long>();
            var working = new List<long>();
            foreach (var cProp in CheckedProperties)
            {
                if (Convert.ToString(cProp).Substring(0, 4).Contains("1000"))
                {
                    master.Add(Convert.ToInt64(Convert.ToString(cProp).Substring(4)));
                }
                else if (Convert.ToString(cProp).Substring(0, 4).Contains("2000"))
                {
                    working.Add(Convert.ToInt64(Convert.ToString(cProp).Substring(4)));
                }
            }

            if (master.Count > 0)
            {  
                DataAccess da = new DataAccess();
                DataTable ds = da.ExecuteSQL(string.Format("deleteArchiveRowFromMasterList @PropertyIDList = '{0}'", 
                    string.Join(",", master.ToArray()))); 
                
                // clear files for all the properties that does not exists in master list
                
                foreach (DataRow dr in ds.Rows)
                {
                    var path = Server.MapPath("~/PropertiesFiles/Archives/MasterList/");
                    string propDir = Path.Combine(path, dr["Location"].ToString());
                    string propDirToAdd = Path.Combine(Server.MapPath("~/PropertiesFiles/LVREO/"), dr["Location"].ToString());

                    try
                    {
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        if (Directory.Exists(propDir))
                            Directory.Move(propDir, propDirToAdd);
                    }
                    catch (Exception ex)
                    {
                    }
                }

            }

            if (working.Count > 0)
            {
                DataAccess da = new DataAccess();
                DataTable ds = da.ExecuteSQL(string.Format("deleteArchiveRowFromWorkingList @PropertyIDList = '{0}'",
                    string.Join(",", working.ToArray())));

                // clear files for all the properties that does not exists in master list
                
                foreach (DataRow dr in ds.Rows)
                {
                    var path = Server.MapPath("~/PropertiesFiles/Archives/WorkingList/");
                    string propDir = Path.Combine(path, dr["Location"].ToString());
                    string propDirToAdd = Path.Combine(Server.MapPath("~/PropertiesFiles/LVREO/"), dr["Location"].ToString());

                    try
                    {
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        if (Directory.Exists(propDir))
                            Directory.Move(propDir, propDirToAdd);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            CheckedProperties.Clear();
            Grid.Rebind();      
        }    
    }

    class CheckBoxedColumn : ITemplate
    {
        string columnName;

        public CheckBoxedColumn(string columnName)
        {
            this.columnName = columnName;
        }

        public void InstantiateIn(Control container)
        {
            CheckBox cb = new CheckBox();
            cb.ID = "checkBox";
            cb.AutoPostBack = true;
            cb.DataBinding += new EventHandler(cb_DataBinding);
            cb.CheckedChanged += new EventHandler(cb_CheckedChanged);

            container.Controls.Add(cb);
        }

        void cb_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            GridDataItem container = (GridDataItem)cb.NamingContainer;
            long propId = Convert.ToInt64(container.GetDataKeyValue("PropertyId"));

            if (cb.Checked)
            {
                if (!Archive.CheckedProperties.Contains(propId))
                    Archive.CheckedProperties.Add(propId); 
            }
            else
            {
                Archive.CheckedProperties.Remove(propId);  
            }
        }

        void cb_DataBinding(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            GridDataItem container = (GridDataItem)cb.NamingContainer;

            long a = Convert.ToInt64(container.GetDataKeyValue("PropertyId"));

            long propId = Convert.ToInt64(container.GetDataKeyValue("PropertyId"));
            cb.Checked = Archive.CheckedProperties.Contains(propId); 
        }
    }
}